<template>
  <el-dialog v-model="dialogVisible" title="新建文件/文件夹">
    <el-form :model="form" label-width="120px">
      <!-- File Type Selection -->
      <el-form-item label="类型">
        <el-select v-model="form.fileType" placeholder="请选择类型">
          <el-option
            v-for="item in fileTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- File Upload (shown when fileType is 1) -->
      <el-form-item label="上传文件" v-if="form.fileType === 1">
          <el-upload
            class="upload-demo"
            :auto-upload="false"
            :on-change="handleFileChange"
            :show-file-list="false"
          >
            <el-button type="primary">选择文件</el-button>
            <span v-if="form.fileName" style="margin-left: 10px">{{ form.fileName }}</span>
          </el-upload>
        </el-form-item>

      <!-- Folder Name (shown when fileType is 2) -->
      <el-form-item label="文件夹名称" v-if="form.fileType === 2">
        <el-input v-model="form.folderName" placeholder="请输入文件夹名称" />
      </el-form-item>

      <!-- Permission Type Selection -->
      <el-form-item label="权限类型">
        <el-select v-model="form.permissionType" placeholder="请选择权限类型">
          <el-option
            v-for="item in permissionTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- Department Selection (shown when permissionType is 1) -->
      <el-form-item label="选择部门" v-if="form.permissionType === 1">
        <el-select v-model="form.refId" placeholder="请选择部门">
          <el-option
            v-for="item in depList"
            :key="item.did"
            :label="item.dname"
            :value="item.did"
          />
        </el-select>
      </el-form-item>

      <!-- Employee Selection (shown when permissionType is 2) -->
      <el-form-item label="选择员工" v-if="form.permissionType === 2">
        <el-select v-model="form.refId" placeholder="请选择员工">
          <el-option-group
            v-for="group in depEmpList"
            :key="group.deptName"
            :label="group.deptName"
          >
            <el-option
              v-for="emp in group.empList"
              :key="emp.eid"
              :label="emp.ename"
              :value="emp.eid"
            />
          </el-option-group>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { ref, reactive } from 'vue'
import req from '@/request'
import { ElMessage } from 'element-plus'

// 枚举定义
const fileTypeOptions = [
  { value: 1, label: '文件' },
  { value: 2, label: '文件夹' }
]

const permissionTypeOptions = [
  { value: 0, label: '全部可见' },
  { value: 1, label: '部门可见' },
  { value: 2, label: '某个人可见' },
  { value: 3, label: '自己可见' }
]

const emit = defineEmits(['add-ok'])

// 表单数据
const form = reactive({
  fileType: 1,
  folderName: '',
  permissionType: 0,
  refId: null,
  fileName: '' // 新增 fileName 字段
})

const file = ref(null)
const dialogVisible = ref(false)
const folder = ref(null)

// 修改文件变更处理函数
const handleFileChange = (uploadFile) => {
  file.value = uploadFile.raw
  form.fileName = uploadFile.name // 更新文件名显示
}

// 部门员工信息
const depEmpList = ref([])
const getDepEmpList = async () => {
  const res = await req.get('/info/emp/dept/detail')
  depEmpList.value = res.data
  console.log("部门员工信息:",depEmpList.value)
}
getDepEmpList()

// 部门信息
const depList = ref([])
const getDepList = async () => {
  const res = await req.get('/info/emp/dep')
  depList.value = res.data
  console.log("部门信息:",depList.value)
}
getDepList()


const open = (_folder = null) => {
  dialogVisible.value = true
  folder.value = _folder
  
  // 重置表单
  form.fileType = 1
  form.folderName = ''
  form.permissionType = 0
  form.refId = null
  file.value = null
}

const submit = async () => {
  // 基本验证
  if (form.fileType === 1 && !file.value) {
    ElMessage.error('请选择要上传的文件')
    return
  }
  
  if (form.fileType === 2 && !form.folderName) {
    ElMessage.error('请输入文件夹名称')
    return
  }

  const formData = new FormData()
  formData.append('fileType', form.fileType.toString())
  
  if (form.fileType === 1) {
    formData.append('file', file.value)
  } else {
    formData.append('folderName', form.folderName)
  }
  
  if (folder.value?.id) {
    formData.append('folderId', folder.value.id)
  }
  
  formData.append('permissionType', form.permissionType.toString())
  
  if (form.permissionType === 1 || form.permissionType === 2) {
    if (!form.refId) {
      ElMessage.error('请选择部门或员工')
      return
    }
    formData.append('refId', form.refId.toString())
  }
  
  try {
    const res = await req.post('/file/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (res.success) {
      ElMessage.success('创建成功')
      dialogVisible.value = false
      // 触发父组件事件
      emit('add-ok')
    } else {
      ElMessage.error(res.message || '创建失败')
    }
  } catch (error) {
    console.error('上传错误:', error)
    ElMessage.error(error.response?.data?.message || '创建失败')
  }
}

defineExpose({
  open
})
</script>

<style>
.upload-demo {
  display: flex;
  align-items: center;
}
</style>